<template>
  <div>
    <el-dialog
        v-model="visibleModel"
        title="选择待送货销售订单"
        width="900"
        :style="[
            !isFullScreen && { height:'65%', width:'100%', maxWidth: '800px' },
            { display: 'flex', flexDirection: 'column' }
        ]"
        align-center
        draggable
        overflow
        :before-close="handleClose"
        :close-on-click-modal="false"
        :fullscreen="isFullScreen"
    >
        <div class="table-box">
            <el-table
                ref="orderListTableRef"
                style="height:100%;"
                :data="orderStore.orderList"
                :span-method="objectSpanMethod"
                @selection-change="handleSelectionChange"
                :cell-style="{ textAlign: 'center' }"
                :header-cell-style="{ textAlign: 'center' }" 
                v-loading="loading"
                element-loading-text="待送货订单数据加载中..."
                border
            >
                <el-table-column prop="selection" type="selection" width="40" fixed :selectable="orderSelectable"/>
                <el-table-column prop="clientName" label="客户" width="120" />
                <el-table-column prop="skuName" label="商品名称" width="120" />
                <el-table-column prop="skuBrand" label="商品牌号" width="100" />
                <el-table-column prop="internalBrand" label="内部牌号" width="100" />
                <el-table-column prop="specification" label="规格型号" width="140" />
                <el-table-column prop="orderState" label="订单状态" width="100">
                    <template #default="scope">
                        <el-tag
                            :type="handleOrderState(scope.row.orderState)"
                        >
                            {{ scope.row.orderState }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="unitPrice" label="单价" width="100"/>
                <el-table-column prop="amount" label="金额" width="110"/>
                <el-table-column prop="quantity" label="订单量" width="90" />
                <el-table-column prop="unit" label="订货单位" width="90" />
                <el-table-column prop="byQuantity" label="按数量" width="80" >
                  <template #default="scope">
                      <span>{{ scope.row.byQuantity === "1" ? "是" : "否" }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="weight" label="订货重量" width="100">
                    <template #default="scope">
                        <span>{{ scope.row.weight ?? "N/A" }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="actualDeliver" label="实送" width="90"/>
                <el-table-column prop="oweDeliver" label="欠送" width="90"/>
                <el-table-column prop="orderDt" label="下单日期" width="120"/>
                <el-table-column prop="scheduledDt" label="要求送达日期" width="130"/>
                <el-table-column prop="orderId" label="订单号" width="130" show-overflow-tooltip />
                <el-table-column prop="remark" label="备注" width="130" show-overflow-tooltip />
            </el-table>
        </div>
        <template #footer>
            <div style="margin: 0 10px; display: flex; overflow: hidden;">
                <el-button type="primary" style="width: 100px;"
                    @click="handleSelect(currentOrder[0])"
                >
                    确定
                </el-button>
                <el-button icon="FullScreen" type="primary" plain style="width: 100px;" @click="isFullScreen = !isFullScreen">
                    {{ !isFullScreen ? "全屏展示" : "退出全屏" }}
                </el-button>
                <el-button plain style="width: 100px;" @click="handleCancel">
                    取消
                </el-button>
            </div>
            <div class="pagination-box">
                <el-pagination 
                    layout="sizes, prev, pager, next" 
                    :total="total"
                    v-model:current-page="pageNum"
                    v-model:page-size="pageSize"
                    :page-sizes="[5, 10, 20, 50]"
                    @current-change="handleCurrentChange"
                    @size-change="handleSizeChange"
                />
            </div>
        </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue';
import { useOrderStore } from '@/stores/sale/order'
import { useDeliveryStore } from '@/stores/sale/delivery'
import { getOrderList } from '@/pages/home/views/sale/api/order'
import { getStock } from '@/pages/home/views/sale/api/delivery';
import { dragTable } from '@/pages/home/views/sale/utils/dragTable'

const visibleModel = defineModel()
const orderStore = useOrderStore()
const deliveryStore = useDeliveryStore()
const pageNum = ref(1)
const pageSize = ref(5)
const total = ref(0)
const currentOrder = ref('')
const orderListTableRef = ref()
const loading = ref(true)
const isFullScreen = ref(false)

const handleClose = (done) => {
    isFullScreen.value = false; 
    done()
}
const handleCancel = () => {
    visibleModel.value = false;
    isFullScreen.value = false;
    orderListTableRef.value.clearSelection()
}
const objectSpanMethod = ({ column, rowIndex }) => {
    if (["clientName", "clientCode", "orderId", "remark"].includes(column.property)) {
        if (rowIndex > 0 && orderStore.orderList[rowIndex]["orderId"] === orderStore.orderList[rowIndex - 1]["orderId"]) {
            return {
                rowspan: 0,
                colspan: 0,
            }
        }
        return {
            rowspan: getRowspan("orderId", rowIndex),
            colspan: 1,
        }
    }
}
const getRowspan = (key, rowIndex) => {
    let rowspan = 1;
    let curVal = orderStore.orderList[rowIndex][key];
    for (let i = rowIndex + 1; i < orderStore.orderList.length; i++) {
        if (orderStore.orderList[i][key] === curVal) {
            rowspan++;
        }
        else break
    }
    return rowspan;
}
const handleSelect = async (row) => {
  for(let key in row){
    deliveryStore.delivery[key] = row[key]
  }
  deliveryStore.delivery.shouldDeliver = row.oweDeliver
  visibleModel.value = false
  orderListTableRef.value.clearSelection()
  const stockData = await getStock(row.skuId)
  deliveryStore.delivery.inventoryPcs = parseFloat(stockData.data.stockPcs)
  deliveryStore.delivery.inventoryWeight = parseFloat(stockData.data.stockWeight)
}
const handleCurrentChange = (val) => {
    pageNum.value = val
    getTableData()
}
const handleSizeChange = (val) => {
    pageSize.value = val
    getTableData()
}
const handleOrderState = (row) => {
  switch (row) {
    case "已完成":
      return "success"
    case "部分送货":
      return "warning"
    case "待送货":
      return "danger"
    default:
      return "info"
  }
}
const orderSelectable = (row) => {
    return row.orderState === "待送货" || row.orderState === "部分送货";
}
const handleSelectionChange = (rows) => {
    if(rows.length > 1){
        orderListTableRef.value.toggleRowSelection(rows.shift(), false)
    }
    currentOrder.value = rows
}
const getTableData = async () => {
    loading.value = true
    const orderData = await getOrderList({
        clientName: "",
        skuName: "",
        orderDtFrom: "",
        orderDtTo: "",
        scheduledDtFrom: "",
        scheduledDtTo: "",
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        orderState: "未完成"
    })
    orderStore.orderData = orderData.data.data.list
    total.value = orderData.data.data.total
    orderStore.getOrderList()
    loading.value = false
    console.log("orderData:", orderData.data)
}

onMounted(() => {
    getTableData()
})

defineExpose({
    dragTable: () => dragTable(orderListTableRef),
    getTableData
})
</script>

<style scoped>
.table-box {
    height: 100%;
    border: none;
}
:deep(.el-dialog__body) {
    overflow: auto;
    flex: 1;
}
:deep(.el-dialog__footer) {
    width: 100%;
    display: flex;
    justify-content: space-between;
}
.el-table {
    --el-table-header-bg-color: var(--el-bg-color-page);
    --el-table-border-color: var(--el-border-color-dark);
    --el-table-header-text-color: var(--el-text-color-primary);
}
:deep(th:nth-of-type(1) .cell) {
    display: none;
}

:deep(th.el-table__cell){
  border-bottom: var(--el-table-border) !important;
}
:deep(.el-table-fixed-column--left){
  outline: var(--el-table-border);
  border: none !important;
}
:deep(.el-table-fixed-column--right){
  outline: var(--el-table-border);
  border: none !important;
}
</style>